using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using PackTracker.Business;

namespace PackTracker.UserControls
{
	public partial class EnderecoEditar : UserControl
	{
		protected void Page_Load(object sender, EventArgs e)
		{
			if (!IsPostBack)
			{
				enderecoForm.DefaultMode = getEndereco().IsNew ? FormViewMode.Edit : FormViewMode.ReadOnly;
				ApplyAuthorizationRules();
			}
		}

		#region Metodos privados

		private void ApplyAuthorizationRules()
		{
			//enderecoButton.Visible = PackTracker.Business.Endereco.CanAddObject();
		}

		private void setEndereco(Endereco endereco, bool salvar)
		{
			if (salvar)
			{
				endereco = endereco.Save();
				ViewState["Endereco"] = Endereco.GetEndereco(endereco.Id);
			}
			else
			{
				ViewState["Endereco"] = endereco;
			}
		}

		protected Endereco getEndereco()
		{
			int enderecoId = 0;
			Endereco endereco = ViewState["Endereco"] as Endereco;

			if (endereco == null)
			{
				if (!String.IsNullOrEmpty(Request.QueryString["EnderecoId"]))
					int.TryParse(Request.QueryString["EnderecoId"].ToString(), out enderecoId);

				endereco = (enderecoId == 0) ? Endereco.NewEndereco() : Endereco.GetEndereco(enderecoId);
				ViewState.Add("Endereco", endereco);
			}
			return endereco;
		}

		#endregion

		#region EnderecoForm

		protected void enderecoForm_ItemUpdated(object sender, FormViewUpdatedEventArgs e)
		{
			Endereco endereco = getEndereco();
			Csla.Data.DataMapper.Map(e.NewValues, endereco, "Id");
			setEndereco(endereco, true);
			
			enderecoForm.DefaultMode = FormViewMode.ReadOnly;
            enderecoForm.DataBind();
		}
		
        protected void enderecoForm_ItemCommand(object sender, FormViewCommandEventArgs e)
        {
            switch (e.CommandName)
            {
                case "Cancel":
                    enderecoForm.DefaultMode = FormViewMode.ReadOnly;
                    enderecoForm.DataBind();
                    break;
                case "Edit":
                    enderecoForm.DefaultMode = FormViewMode.Edit;
                    ApplyAuthorizationRules();
                    break;
            }
        }
        
        protected void enderecoForm_ItemDeleting(object sender, FormViewDeleteEventArgs e)
        {
            Endereco.DeleteEndereco(getEndereco().Id);
        }
		
		#endregion
		
		#region DataSources

		protected void enderecoDataSource_SelectObject(object sender, Csla.Web.SelectObjectArgs e)
		{
			e.BusinessObject = getEndereco();
		}

		#endregion
		
    }
}
